import React, { Component } from 'react'
// 引入store, 用于获取状态
import store from '../../redux/store'
// 引入actionCreator, 用于创建action对象
import {createAddAction, createMinusAction} from '../../redux/count_action'

export default class Count extends Component {
    // 挂载时就开始监测, 为了方便写在入口文件中
    // componentDidMount = () => {
    //     // 检测redux中状态的变化, 只要变化就调用render
    //     store.subscribe(() => {
    //         // redux不更新页面, 需要自行调用setState来调用render()
    //         this.setState({});
    //     })
    // }

    add = () => {
        const { value } = this.selectNum
        // 通知redux进行操作
        store.dispatch(createAddAction(value * 1))
    }

    minus = () => {
        const { value } = this.selectNum
        store.dispatch(createMinusAction(value * 1))
    }

    addIfOdd = () => {
        const count = store.getState()
        const { value } = this.selectNum
        if (count % 2 !== 0)
            store.dispatch({
                type: 'add',
                data: value * 1
            })
    }

    addAsync = () => {
        const count = store.getState()
        const { value } = this.selectNum
        setTimeout(() => {
            store.dispatch({
                type: 'add',
                data: value * 1
            })
        }, 1000)
    }

    render() {
        return (
            <div>
                <h1>当前求和为: {store.getState()}</h1>
                <select ref={c => this.selectNum = c} name="" id="">
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                </select>&nbsp;
                <button onClick={this.add}>+</button>&nbsp;
                <button onClick={this.minus}>-</button>&nbsp;
                <button onClick={this.addIfOdd}>当前求和为奇数时, +</button>&nbsp;
                <button onClick={this.addAsync}>异步, +</button>&nbsp;
            </div>
        )
    }
}
